<!--
 * @Author: your name
 * @Date: 2021-08-02 01:29:27
 * @LastEditTime: 2022-10-25 15:30:26
 * @LastEditors: 张祥 zhangxiang@sidri.com
 * @Description: In User Settings Edit
 * @FilePath: \aircityinit\src\components\player\player.vue
-->
<template>
  <div id="player"></div>
</template>
<script>
import OnEvent from "@/AirCityUtils/Event";
import OnReady from "@/AirCityUtils/onReady";
import { mapState, mapActions } from "vuex";
import { ManageCommand } from "./connect";
export default {
  data() {
    return {
      ws: null,
      authorization: null,
      Version: null,
    };
  },
  computed: {
    // 获取AirCity模块里的状态
    ...mapState("AirCity", ["AirCityApi", "AirCityPlayer"]),
  },
  watch: {},
  methods: {
    ...mapActions({
      //异步action
      setAirCityApi_act: "AirCity/setAirCityApi_act",
      setAirCityPlayer_act: "AirCity/setAirCityPlayer_act",
    }),
    connect() {
      this.ws = new WebSocket(`ws://${window.HostConfig.Manager}/manager`);
      this.ws.onopen = () => {
        // 连接成功时进行登录
        this.sendData({
          command: ManageCommand.Login,
          userName: window.userInfo ? window.userInfo.UserName : "admin",
          password: window.userInfo ? window.userInfo.PassWord : "admin",
        });
      };
      this.ws.onmessage = (event) => {
        let o = JSON.parse(event.data);
        console.log(o);

        //检查登录是否过期
        if (o.result == 1 && this.Version === 5.0) {
          this.$message("登录失败或者登录信息已过期，请重新登录!");
          return;
        }
        switch (o.command) {
          case -1:
            {
              if (o.result == 0) {
                this.authorization = o.authorization; //保存
                this.$message.success("登录成功");

                this.sendData({
                  command: ManageCommand.GetOneFreeInstance,
                  details: true,
                  connections: true,
                });
              }
            }
            break;
          case 1:
            break;
          case 6:
            break;
          case 100:
            break;
          case 102:
            /**
             * @5.0版本的实例连接:
             * @param {id}
             * @return {initInterface()}
             */
            console.log(o, "oooooooooooooooooooo");
            // 这里的返回是获取到空闲实例（或者正在运行的实例）
            // 在这里进行实例的连接
            this.initInterface_5(true, o.id);
            window.addEventListener("resize", this.onResize);
            window.addEventListener(
              "beforeunload",
              this.beforeunloadHandler,
              false
            );
            break;
        }
      };
      this.ws.onclose = () => {
        this.ws = null;
        // this.connect();
      };

      this.ws.onerror = function () {
        this.ws = null;
      };
    },
    // 发送WebSocket指令
    sendData(o) {
      //5.0集群版cloud需要在发送之前需要附加上授权信息以进行权限验证
      if (this.authorization) {
        o.authorization = this.authorization;
      }
      this.ws.send(JSON.stringify(o));
    },
    // 5.0连接实例
    initInterface_5(iscloud, IID) {
      let log = () => {};
      //onReady
      let _onReady = () => {
        OnReady();
        this.onResize();
      };
      //onEvent
      let _onEvent = (e) => {
        OnEvent(e);
      };
      let _onClose = (e) => {
        console.log(e);
        //如果没有指定工程文件，则加上pid参数，pid=-1让服务器随便指定一个工程文件
        //如果想访问指定的工程文件，则明确指定pid, 例如pid=3
        if (e && e.code == 4009) {
          if (location.href.indexOf("?") == -1) location.href += "?pid=-1";
          else location.href += "&pid=-1";
        }
      };
      // _onApiVersion
      let _onApiVersion = (e) => {
        console.log(e, "_onApiVersion");
      };
      //AirCityAPI初始化选项
      let apiOptions = {
        onReady: _onReady,
        onApiVersion: _onApiVersion,
        onEvent: _onEvent,
        onLog: log,
        useColorLog: false, //仅用于SDK测试页面，二次开发请设置为false
      };
      //2021.07.30 因为支持了端口映射，所以这个地方要处理一下内外网host的问题
      //因为HostConfig里自动生成的是内网地址，所以这个地方要根据当前访问的地址替换一下
      // if (location.protocol != "file:") {
      //   HostConfig.Player =
      //     location.hostname + ":" + HostConfig.Player.split(":")[1];
      // }
      //Cloud需要同时初始化AirCityAPI和AirCityPlayer
      if (iscloud) {
        //AirCityPlayer
        let options;
        if (document.getElementById("player")) {
          //需要显示视频流
          options = {
            iid: IID, //如果想连接指定的云渲染实例，可以指定这个参数
            pid: null,
            domId: "player",
            apiOptions: apiOptions,
            showMarker: false,
            showStartupInfo: false,
            onclose: _onClose,
          };
        } else {
          options = {
            iid: IID, //不带视频流的连接必须指定云渲染实例
            pid: null,
            apiOptions: apiOptions,
          };
        }
        let aircityPlayer = new window.AirCityPlayer(
          window.HostConfig.Player,
          options
        );
        console.log(aircityPlayer, "aircityPlayer");
        // 提交仓库
        this.setAirCityPlayer_act(aircityPlayer);
        //对于Cloud应用可以不用显式的创建AirCityAPI对象，只需要在AirCityPlayer创建参数里指定apiOptions，就会自动创建。
        let aircityApi = aircityPlayer.getAPI();
        console.log(aircityApi, "aircityApi");
        console.log(window.__g, "__g");
        // 提交仓库
        this.setAirCityApi_act(aircityApi);
      }
    },

    onResize() {
      console.log("onResize");
      // let player = document.getElementById("player");
      // let innerHeight = window.innerHeight;
      // let innerWidth = window.innerWidth;
      // player.style.height = innerHeight;
      // player.style.width = innerWidth;
      this.AirCityPlayer.resize && this.AirCityPlayer.resize();
      this.AirCityPlayer.ui_resize && this.AirCityPlayer.ui_resize();
    },
    beforeunloadHandler() {
      console.log("页面刷新前");
      // window.__g.reset();
    },
  },
  created() {},
  mounted() {
    this.connect();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {
    console.log("断开实例");
    this.AirCityApi.destroy();
    this.AirCityPlayer.destroy();
    // window.removeEventListener('load', this.onLoad)
    window.removeEventListener("resize", this.onResize);
    window.removeEventListener("beforeunload", this.beforeunloadHandler);
  },
  destroyed() {},
  activated() {},
  components: {},
};
</script>

<style lang="scss" scoped>
#player {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 0;
}
</style>
